import dayjs from "dayjs";
import { http } from "@/lib";
import apis from '@/apis'

const OSS = require('ali-oss')

const ossConfig = {
  /* 泸州老窖OSS */
  // region: 'oss-cn-shanghai',
  region: 'oss-accelerate',
  bucket: 'lzlj-jxsmh'
}

const uploadProgress = function (p) {
  return function (done) {
    console.log('progress',p)
    // var bar = document.getElementById('progress-bar')
    // bar.style.width = Math.floor(p * 100) + '%'
    // bar.innerHTML = Math.floor(p * 100) + '%'
    done()
  }
}

const fileKeyFormat = (modelPath,file,key?) => {
  const { name } = file
  const date = dayjs().format('YYYY-MM-DD')
  const time = dayjs().format('YYYYMMDDHHmmss')
  const fileName = key?('/'+key):time+name
  let pathName = modelPath
  /* if (type.includes('image')) {
    pathName = 'images'
  } else {
    pathName = 'files'
  } */
  key = pathName+'/'+date+'/'+fileName
  // key为oss里文件保存路径，oss里的资源大小写敏感，key尽量使用全小写，多个单词可以用 - 分隔。
  return key
}
// 获取stsToken
const applyTokenDo = (func) => {
  return http.get(apis.OSSTstToken).then(res=>{
    const creds:any = res.data
    const client = new OSS({
      region: ossConfig.region,
      accessKeyId: creds.accessKeyId,
      accessKeySecret: creds.accessKeySecret,
      stsToken: creds.securityToken,
      bucket: ossConfig.bucket
    })
    return func(client)
  })
}

const ossHttp = {
  put: (modelPath,file,putType='text/plain',key?) => {
    return applyTokenDo((client)=>{
      key = fileKeyFormat(modelPath,file)
      return client.put(key, file,{ putType })
    })
  },
  multipartUpload: (modelPath,file,putType='text/plain',progress?,key?) => {
    progress = uploadProgress
    return applyTokenDo((client)=>{
      key = fileKeyFormat(modelPath,file)
      return client.multipartUpload(key,file,{
        progress,
      })
    })
  },
  download: (url) => {
    window.open(url)
  },
  signatureDown: (key) => {
    ossHttp.signatureUrl(key).then(url=>{
      window.open(url)
    })
  },
  signatureUrl: (key) => {
    return applyTokenDo((client)=>{
      const url = client.signatureUrl(key, {expires: 3600}) // URL的有效时间默认为半个小时
      return url
    })
  },
  deleteMulti: (keys:string[]) => {
    return applyTokenDo((client)=>{
      try {  
        keys = Array.isArray(keys)?keys:[keys]
        // 统一decodeURI处理传入的key
        keys = keys.map(key=>decodeURI(key))
        let  result = client.deleteMulti(keys,{
          quiet: true
        })
        return result
      } catch (e) {
        console.log(e)
      }
    })
  }
}

export default ossHttp